import collections
import time
from broker.tws.constant.Constant import *

class OrderReq:

    def __init__(self):
        self.symbol = ""    # 股票：US.APPL   期权：US.UPST211112C350000

        self.acctId = 0   # Order identifier
        self.conid = ""   # Contract identifier
        self.secType = SecType.STK  # Asset class
        self.cOID = "%s" % int(time.time())
        self.orderType = OrderType.LMT
        self.listingExchange = ListingExchange.SMART

        self.side = Side.BUY   # 交易买卖方向
        self.price = 0.0
        self.quantity = 0   # 委托数量
        self.ticker = ""
        self.tif = TimeInForce.DAY
        self.useAdaptive = False
        self.isCcyConv = False

    def __str__(self):
        return "%s" % self.to_map()

    @staticmethod
    def stock(symbol: str, price, side: str, quantity):
        req = OrderReq()
        req.symbol = symbol
        req.price = price
        req.side = side
        req.quantity = quantity
        req.secType = SecType.STK
        if symbol.startswith("US."):
            req.listingExchange = ListingExchange.SMART
            req.ticker = symbol.replace("US.", "")
        elif symbol.startswith("HK."):
            req.listingExchange = ListingExchange.SEHK
            req.ticker = symbol.replace("US.", "")
        return req

    @staticmethod
    def option(symbol: str, price, side, quantity):
        req = OrderReq()
        req.symbol = symbol
        req.price = price
        req.side = side
        req.quantity = quantity
        req.secType = SecType.OPT
        if symbol.startswith("US."):
            req.listingExchange = ListingExchange.SMART
        elif symbol.startswith("HK."):
            req.listingExchange = ListingExchange.SEHK
        return req

    def to_map(self):
        data = collections.defaultdict(list)
        data["acctId"] = self.acctId
        data["conid"] = self.conid
        data["secType"] = "%s:%s" % (self.conid, self.secType)
        data["cOID"] = self.cOID
        data["orderType"] = self.orderType
        data["listingExchange"] = self.listingExchange
        data["isSingleGroup"] = True
        data["outsideRTH"] = True
        data["side"] = self.side
        data["price"] = self.price
        data["quantity"] = self.quantity
        data["ticker"] = self.ticker
        data["tif"] = self.tif
        data["useAdaptive"] = False
        data["isCcyConv"] = False
        return data

